
#include "stdafx.h"
#include "game_main.h"
#include "game_scene.h"
#include "game_actor.h"

static bool _parse_process(const dsVECTOR<dsSTRING> & args, dsSTRING & line, std::istream & input)
{
   dsVECTOR<dsSTRING> params;

   if (args[0] == "startpos") {
      while (ReadNextLine(input, line)) {
         if (line[0] == '#') {
            return ;
         }

         ds::Tokenize(line, "= ,", params);
         if (params.IsEmpty()) {
            continue;
         }
      }

      return ;
   }

   line = dsSTRING();

   return true;
}

static void _parse_scene(const dsSTRING & filename)
{
   std::ifstream input(filename.CStr());
   if (!input) {
      ShowErrorMsg("Failed to open scene: %s", filename.CStr());
      return ;
   }

   dsVECTOR<dsSTRING> args;

   dsSTRING line;
   bool readNextLine = true;
   while (!readNextLine || ReadNextLine(input, line)) {
      readNextLine = true;

      if (line[0] == '#') {
         ds::Tokenize(line, " ,#", args);
         if (args.IsEmpty()) {
            continue;
         }

         if (!_parse_process(args, line, input)) {
            return ;
         }

         readNextLine = line.IsEmpty();
         continue;
      }
   }
}

/******************************************************************************/
/* game_load_level
/*
/******************************************************************************/
void game_load_level(const dsSTRING & sceneName)
{
   ASSERT(gameState.scene == NULL);
   gameState.scene = NewObj(GAME_SCENE);

   dsSTRING scenesPath = gameConfig->GetValue("path", "scenes", ".");
   dsSTRING filename = dsSPrintf("%s\\%s.scene", scenesPath.CStr(), sceneName.CStr());

   _parse_scene(filename);
}

/******************************************************************************/
/* GAME_SCENE::~GAME_SCENE
/*
/******************************************************************************/
GAME_SCENE::~GAME_SCENE(void)
{
   for (int index = 0; index < actors.size(); ++index) {
      Delete(actors[index]);
   }

   actors.clear();
}